// firstPackage/pages/reportModule/reportRecordDetail/reportRecordDetail.js

import {
  queryRecommendDetail,
  updateRecommendDetail
} from "../../../../service/custom_service"
import {
  chooseMultipleImgUploadQiniuAction
} from "../../../../service/upload_service"
import debounce from "../../../../tools/debounce"
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    bottomTitle: "提交",
    followArr: [
      // {
      //   text: '已到访',
      //   desc: '2020年6月7日(本人到访)',
      // },
      // {
      //   text: '步骤二',
      //   desc: '描述信息',
      // },
      // {
      //   text: '步骤三',
      //   desc: '描述信息',
      // },
    ],
    checkArr: [
      { type: 1 }, { type: 1 }, { type: 1 }
    ],
    detailId: null,//详情id
    formData: {

    },//详情数据
    //提交数据
    subFormData: {
      buyHouseNumber: "",
      id: null,
      images: [],
      recordId: null,
      status: null,
      totalPrice: null,
    },
    //报备列表
    recordList: [

    ],
    currentSubmitStatus: null,//最终提交数据的status
    lastExamineStatus: null,
    invalidStatus: null,//是否是无效报备
    isReportDeveloper: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        detailId: options.id
      })
    }
    this.queryRecommendDetail();
  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
  },

  //查询报备详情:
  queryRecommendDetail() {
    wx.showLoading();
    queryRecommendDetail(this.data.detailId).then(res => {
      wx.hideLoading();
      console.log("JJLog:获取到的报备详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (!res.data.isReportDeveloper) {
          this.setData({
            formData: res.data,
            isReportDeveloper: false
          })
          return;
        }

        if (res.data.status == -1) {
          this.setData({
            formData: res.data,
            currentSubmitStatus: 5,
            lastExamineStatus: 2,
            invalidStatus: true,//无效报备
          })
          return;
        }
        this.setData({
          formData: res.data,
          recordList: res.data.records,
          lastExamineStatus: res.data.records[res.data.records.length - 1].examineStatus,
          currentSubmitStatus: res.data.status
        })
        this.setData({
          'subFormData.id': res.data.id,
        })
        if (this.data.lastExamineStatus == 3) {
          let lastItem = res.data.records[res.data.records.length - 1];
          this.setData({
            'subFormData.images': lastItem.images,
            'subFormData.recordId': lastItem.id,
            'subFormData.status': res.data.status,
            'subFormData.buyHouseNumber': res.data.buyHouseNumber,
            'subFormData.totalPrice': res.data.totalPrice
          })
        }

        this.dealFllowArr(res.data.records);
      }
    }).catch(err => {
      console.error("JJLog:queryRecommendDetail", err);
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
    })
  },
  //处理审核记录
  dealFllowArr(arr) {
    let tempArr = [];
    arr.forEach((item) => {
      let obj = {
        text: "",
        desc: "",
      }
      if (item.status == 2) {
        obj.text = "已报备"
      } else if (item.status == 3) {
        obj.text = "到访"
      } else if (item.status == 4) {
        obj.text = "认购"
      } else if (item.status == 5) {
        obj.text = "签约"
      }
      if (item.examineStatus == 0) {
        obj.desc = "资料未提交"
      } else if (item.examineStatus == 1) {
        obj.desc = "资料审核中"
      } else if (item.examineStatus == 2) {
        obj.desc = "资料审核通过"
      } else if (item.examineStatus == 3) {
        obj.desc = "失败原因：" + item.remark
      }
      tempArr.push(obj);
    })
    this.setData({
      followArr: tempArr
    })
  },
  //上传资料图片
  pushRecordImg(e) {
    let index = e.currentTarget.dataset.index;
    let recordItem = e.currentTarget.dataset.item;
    let imgArr = recordItem.images || [];
    let status = recordItem.status;
    chooseMultipleImgUploadQiniuAction('recordImg').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })
      res.forEach((item) => {
        let obj = {
          "type": 1,
          "url": item.complateUrl,
        }
        imgArr.push(obj);
      })
      recordItem.images = imgArr;
      let changeItem = 'recordList[' + index + ']';
      this.setData({
        [changeItem]: recordItem,
        'subFormData.images': imgArr,
        'subFormData.status': status,
        'subFormData.recordId': recordItem.id
      })

    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })

  },
  //删除一张图片
  cancelOneImg(e) {
    let item = e.currentTarget.dataset.item;
    let imgIndex = e.currentTarget.dataset.imgindex;
    let index = e.currentTarget.dataset.index;
    let images = item.images;
    images.splice(imgIndex, 1);
    item.images = images;
    let changeItem = 'recordList[' + index + ']';
    this.setData({
      [changeItem]: item,
      'subFormData.images': images,
    })
  },
  //输入房号，总价绑定:
  cellInputChange(e) {
    let key = e.currentTarget.dataset.key;
    if (key == "totalPrice") {
      this.setData({
        'subFormData.totalPrice': e.detail.value,
      })
      if (e.detail.value) {
        if (!this.checkNumber(e.detail.value)) {
          wx.showToast({
            title: '认购总价只能填写数字',
            icon: "none"
          })
          this.setData({
            'subFormData.totalPrice': "",
          })
        }
      }
    } else {
      this.setData({
        'subFormData.buyHouseNumber': e.detail.value,
      })
    }
  },

  //提交数据:
  submitAction() {
    if (!this.data.formData.isSubmit) {
      wx.showToast({
        title: '暂时无法提交资料',
        icon: "none"
      })
      return;
    }
    if (this.data.currentSubmitStatus == 3) {
      //提交已认购资料:
      let data = this.data.subFormData;
      if (!data.buyHouseNumber) {
        wx.showToast({
          title: '请输入认购房源房号',
          icon: "none"
        })
        return;
      }
      if (!data.totalPrice) {
        wx.showToast({
          title: '请输入认购房源总价',
          icon: "none"
        })
        return;
      }
    }

    if (this.data.lastExamineStatus == 1) {
      wx.showToast({
        title: "资料审核中，无法提交",
        icon: "none"
      })
      return;
    }
    if (this.data.lastExamineStatus == 2) {
      wx.showToast({
        title: "资料审核成功，不能修改",
        icon: "none"
      })
      return;
    }
    debounce(this.submitInfoRequest);
  },
  //提交数据请求;
  submitInfoRequest() {
    console.log(this.data.subFormData);
    wx.showLoading();
    updateRecommendDetail(this.data.subFormData).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.showToast({
          title: '提交成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 0,
          })
        }, 2000);
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "提交失败",
        icon:"none"
      })
      console.error("JJLog:updateRecommendDetail", err);
    })
  },


  checkNumber(theObj) {
    var reg = /^[0-9]+.?[0-9]*$/;
    if (reg.test(theObj)) {
      return true;
    }
    return false;
  },

})